package cn.bonoon.kernel.support.services.handler;

import java.util.List;

import javax.persistence.EntityManager;

import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.entities.Persistable;

/**
 * <pre>
 * 指定如果删除树；比如：删除一个节点，删除后该节点的子节点都被删除
 * 或者：删除一个节点，该节点下的所有子节点都被移动到根节点下，或其它默认的节点下
 * </pre>
 * @author jackson
 *
 * @param <E>
 */
public class DeleteTreeHandler<E extends Persistable> implements DeleteHandler{
	
	private final DeleteHandler parent;
	private final DeleteHandler nodeHandler;
	private final String loadChildren;
	private final Class<E> entityClass;
	public DeleteTreeHandler(DeleteHandler deleteParent, DeleteHandler deleteChildren, Class<E> entityClass){
		this.parent = deleteParent;
		this.nodeHandler = deleteChildren;
		this.entityClass = entityClass;
		this.loadChildren = "select x from " + entityClass.getName() + " x where x.parent.id=?";
	}
	
	@Override
	public void handler(EntityManager entityManager, OperateEvent event, Persistable entity) {
		//处理子级节点
		visit(entityManager, event, entity);
		
		parent.handler(entityManager, event, entity);
	}
	
	private void visit(EntityManager entityManager, OperateEvent event, Persistable nodes){
		if(null != nodes){
			List<E> items = entityManager.createQuery(loadChildren, entityClass)
					.setParameter(1, nodes.getId()).getResultList();
			for(E node : items){
				visit(entityManager, event, node);
				nodeHandler.handler(entityManager, event, (E)node);
			}
		}
	}
}
